import 'package:flutter/material.dart';
import 'package:myapp/generated/app_strings.dart';
import '../models/community_info.dart';
import '../services/community_storage_service.dart';
import 'package:myapp/src/utils/app_baidu_map_utils.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:myapp/src/services/location_service.dart';
import 'package:uuid/uuid.dart';

///小区编辑页面
class CommunityEditPage extends StatefulWidget {
  final CommunityStorageService storageService;
  final CommunityInfo? community;

  const CommunityEditPage({
    Key? key,
    required this.storageService,
    this.community,
  }) : super(key: key);

  @override
  State<CommunityEditPage> createState() => _CommunityEditPageState();
}

class _CommunityEditPageState extends State<CommunityEditPage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _addressController;
  late TextEditingController _notesController;
  bool _allowDelivery = false;
  bool _hasDoorControl = false;
  bool _hasElevator = false;
  bool _elevatorNeedCard = false;
  bool _isInYuyaoJiangnanSouth = false;
  bool _isInNingciEastNorth = false;
  bool _isInHongtang = false;
  bool _isNearMixc = false;
  bool _isEasyDelivery = false;
  bool _isHardDelivery = false;
  bool _isBusiness = false;
  bool _hasDeliveryCabinet = false;
  List<BuildingPassword> _buildingPasswords = [];
  bool _isLoading = false;
  CommunityInfo? _community;
  String? _province;
  String? _city;
  String? _district;
  double? _latitude;
  double? _longitude;

  @override
  void initState() {
    super.initState();
    final community = widget.community;
    _nameController = TextEditingController(text: community?.name ?? '');
    _addressController = TextEditingController(text: community?.address ?? '');
    _notesController = TextEditingController(text: community?.notes ?? '');
    _allowDelivery = community?.allowDelivery ?? false;
    _hasDoorControl = community?.hasDoorControl ?? false;
    _hasElevator = community?.hasElevator ?? false;
    _elevatorNeedCard = community?.elevatorNeedCard ?? false;
    _isInYuyaoJiangnanSouth = community?.isInYuyaoJiangnanSouth ?? false;
    _isInNingciEastNorth = community?.isInNingciEastNorth ?? false;
    _isInHongtang = community?.isInHongtang ?? false;
    _isNearMixc = community?.isNearMixc ?? false;
    _isEasyDelivery = community?.isEasyDelivery ?? false;
    _isHardDelivery = community?.isHardDelivery ?? false;
    _isBusiness = community?.isBusiness ?? false;
    _hasDeliveryCabinet = community?.hasDeliveryCabinet ?? false;
    _buildingPasswords = community?.buildingPasswords ?? [];
    _community = community;
    _province = community?.province;
    _city = community?.city;
    _district = community?.district;
    _latitude = community?.latitude;
    _longitude = community?.longitude;
  }

  @override
  void dispose() {
    _nameController.dispose();
    _addressController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  Future<void> _getCurrentLocation() async {
    try {
      final location = await LocationService.getCurrentLocation(context);
      if (location != null) {
        // print('设置位置信息: 纬度=${location.latitude}, 经度=${location.longitude}');
        setState(() {
          _addressController.text = location.address;
          _province = location.province;
          _city = location.city;
          _district = location.district;
          _latitude = location.latitude;
          _longitude = location.longitude;
        });
        // print('设置后的状态: 纬度=$_latitude, 经度=$_longitude');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(AppStrings.of(context).getLocationFailed(e.toString()))),
        );
      }
    }
  }

  Future<void> _saveCommunity() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      final community = CommunityInfo(
        id: widget.community?.id ?? const Uuid().v4(),
        name: _nameController.text,
        address: _addressController.text,
        allowDelivery: _allowDelivery,
        hasDoorControl: _hasDoorControl,
        hasElevator: _hasElevator,
        elevatorNeedCard: _elevatorNeedCard,
        isInYuyaoJiangnanSouth: _isInYuyaoJiangnanSouth,
        isInNingciEastNorth: _isInNingciEastNorth,
        isInHongtang: _isInHongtang,
        isNearMixc: _isNearMixc,
        isEasyDelivery: _isEasyDelivery,
        isHardDelivery: _isHardDelivery,
        isBusiness: _isBusiness,
        hasDeliveryCabinet: _hasDeliveryCabinet,
        notes: _notesController.text.isEmpty ? null : _notesController.text,
        createTime: widget.community?.createTime ?? DateTime.now(),
        updateTime: DateTime.now(),
        buildingPasswords: _buildingPasswords,
        province: _province,
        city: _city,
        district: _district,
        latitude: _latitude,
        longitude: _longitude,
      );

      await widget.storageService.saveCommunity(community);
      if (mounted) {
        Navigator.pop(context, true);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(AppStrings.of(context).saveFailed(e.toString()))),
        );
      }
    }
  }

  void _addBuildingPassword() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppStrings.of(context).addBuildingPassword),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              decoration: InputDecoration(
                labelText: AppStrings.of(context).buildingNumber,
                hintText: AppStrings.of(context).buildingNumberHint,
              ),
              onChanged: (value) => _tempBuildingNumber = value,
            ),
            const SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(
                labelText: AppStrings.of(context).password,
                hintText: AppStrings.of(context).passwordHint,
              ),
              onChanged: (value) => _tempPassword = value,
            ),
            const SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(
                labelText: AppStrings.of(context).notes,
                hintText: AppStrings.of(context).notesOptional,
              ),
              onChanged: (value) => _tempNotes = value,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(AppStrings.of(context).cancel),
          ),
          TextButton(
            onPressed: () {
              if (_tempBuildingNumber.isNotEmpty && _tempPassword.isNotEmpty) {
                setState(() {
                  _buildingPasswords.add(BuildingPassword(
                    buildingNumber: _tempBuildingNumber,
                    password: _tempPassword,
                    notes: _tempNotes.isEmpty ? null : _tempNotes,
                  ));
                });
                Navigator.pop(context);
              }
            },
            child: Text(AppStrings.of(context).add),
          ),
        ],
      ),
    );
  }

  void _editBuildingPassword(int index) {
    final password = _buildingPasswords[index];
    _tempBuildingNumber = password.buildingNumber;
    _tempPassword = password.password;
    _tempNotes = password.notes ?? '';

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppStrings.of(context).editBuildingPassword),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              decoration: InputDecoration(
                labelText: AppStrings.of(context).buildingNumber,
                hintText: AppStrings.of(context).buildingNumberHint,
              ),
              controller: TextEditingController(text: _tempBuildingNumber),
              onChanged: (value) => _tempBuildingNumber = value,
            ),
            const SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(
                labelText: AppStrings.of(context).password,
                hintText: AppStrings.of(context).passwordHint,
              ),
              controller: TextEditingController(text: _tempPassword),
              onChanged: (value) => _tempPassword = value,
            ),
            const SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(
                labelText: AppStrings.of(context).notes,
                hintText: AppStrings.of(context).notesOptional,
              ),
              controller: TextEditingController(text: _tempNotes),
              onChanged: (value) => _tempNotes = value,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(AppStrings.of(context).cancel),
          ),
          TextButton(
            onPressed: () {
              if (_tempBuildingNumber.isNotEmpty && _tempPassword.isNotEmpty) {
                setState(() {
                  _buildingPasswords[index] = BuildingPassword(
                    buildingNumber: _tempBuildingNumber,
                    password: _tempPassword,
                    notes: _tempNotes.isEmpty ? null : _tempNotes,
                  );
                });
                Navigator.pop(context);
              }
            },
            child: Text(AppStrings.of(context).save),
          ),
        ],
      ),
    );
  }

  void _deleteBuildingPassword(int index) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppStrings.of(context).confirmDelete),
        content: Text(AppStrings.of(context).confirmDeleteBuildingPassword(_buildingPasswords[index].buildingNumber)),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(AppStrings.of(context).cancel),
          ),
          TextButton(
            onPressed: () {
              setState(() {
                _buildingPasswords.removeAt(index);
              });
              Navigator.pop(context);
            },
            child: Text(AppStrings.of(context).delete),
          ),
        ],
      ),
    );
  }

  String _tempBuildingNumber = '';
  String _tempPassword = '';
  String _tempNotes = '';

  @override
  Widget build(BuildContext context) {
    // print('构建页面: 纬度=$_latitude, 经度=$_longitude');
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.community == null ? AppStrings.of(context).addCommunity : AppStrings.of(context).editCommunity),
        actions: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            child: ElevatedButton(
              onPressed: _saveCommunity,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: Theme.of(context).primaryColor,
                elevation: 2,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              child: Text(
                AppStrings.of(context).save,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(
                  labelText: AppStrings.of(context).communityName,
                  hintText: AppStrings.of(context).communityNameHint,
                  border: const OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return AppStrings.of(context).communityNameRequired;
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: TextFormField(
                      controller: _addressController,
                      decoration: InputDecoration(
                        labelText: AppStrings.of(context).communityAddress,
                        hintText: AppStrings.of(context).communityAddressHint,
                        border: const OutlineInputBorder(),
                        suffixIcon: _addressController.text.isNotEmpty
                            ? IconButton(
                                icon: const Icon(Icons.copy, size: 20),
                                onPressed: () {
                                  Clipboard.setData(ClipboardData(text: _addressController.text));
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(content: Text(AppStrings.of(context).communityAddressCopied)),
                                  );
                                },
                                tooltip: '复制地址',
                                style: IconButton.styleFrom(
                                  foregroundColor: Theme.of(context).primaryColor,
                                ),
                              )
                            : null,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  IconButton(
                    onPressed: _getCurrentLocation,
                    icon: const Icon(Icons.my_location),
                    tooltip: AppStrings.of(context).getCurrentLocation,
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  Expanded(
                    child: TextFormField(
                      initialValue: _latitude?.toStringAsFixed(6),
                      decoration: InputDecoration(
                        labelText: AppStrings.of(context).latitude,
                        hintText: '29.934065',
                        border: const OutlineInputBorder(),
                        prefixIcon: const Icon(Icons.location_on, size: 20),
                      ),
                      keyboardType: const TextInputType.numberWithOptions(decimal: true),
                      onChanged: (value) {
                        if (value.isNotEmpty) {
                          setState(() {
                            _latitude = double.tryParse(value);
                          });
                        }
                      },
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: TextFormField(
                      initialValue: _longitude?.toStringAsFixed(6),
                      decoration: InputDecoration(
                        labelText: AppStrings.of(context).longitude,
                        hintText: '121.536437',
                        border: const OutlineInputBorder(),
                        prefixIcon: const Icon(Icons.location_on, size: 20),
                      ),
                      keyboardType: const TextInputType.numberWithOptions(decimal: true),
                      onChanged: (value) {
                        if (value.isNotEmpty) {
                          setState(() {
                            _longitude = double.tryParse(value);
                          });
                        }
                      },
                    ),
                  ),
                ],
              ),
              if (_latitude != null && _longitude != null) ...[
                const SizedBox(height: 8),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Row(
                    children: [
                      const Icon(Icons.location_on, size: 16, color: Colors.grey),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          '${AppStrings.of(context).latitude}: ${_latitude!.toStringAsFixed(6)}, ${AppStrings.of(context).longitude}: ${_longitude!.toStringAsFixed(6)}',
                          style: const TextStyle(
                            fontSize: 12,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
              const SizedBox(height: 16),
              TextFormField(
                controller: _notesController,
                decoration: InputDecoration(
                  labelText: AppStrings.of(context).notes,
                  hintText: AppStrings.of(context).notesHint,
                  border: const OutlineInputBorder(),
                ),
                maxLines: 3,
              ),
              const SizedBox(height: 16),
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        AppStrings.of(context).facilities,
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 16),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).allowDeliveryBike),
                        value: _allowDelivery,
                        onChanged: (value) => setState(() => _allowDelivery = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).hasDoorControl),
                        value: _hasDoorControl,
                        onChanged: (value) => setState(() => _hasDoorControl = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).hasElevator),
                        value: _hasElevator,
                        onChanged: (value) => setState(() => _hasElevator = value),
                      ),
                      if (_hasElevator)
                        SwitchListTile(
                          title: Text(AppStrings.of(context).elevatorNeedCard),
                          value: _elevatorNeedCard,
                          onChanged: (value) => setState(() => _elevatorNeedCard = value),
                        ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).yuyaoJiangnanSouth),
                        value: _isInYuyaoJiangnanSouth,
                        onChanged: (value) => setState(() => _isInYuyaoJiangnanSouth = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).ningciEastNorth),
                        value: _isInNingciEastNorth,
                        onChanged: (value) => setState(() => _isInNingciEastNorth = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).hongtang),
                        value: _isInHongtang,
                        onChanged: (value) => setState(() => _isInHongtang = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).nearMixc),
                        value: _isNearMixc,
                        onChanged: (value) => setState(() => _isNearMixc = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).easyDelivery),
                        value: _isEasyDelivery,
                        onChanged: (value) => setState(() => _isEasyDelivery = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).hardDelivery),
                        value: _isHardDelivery,
                        onChanged: (value) => setState(() => _isHardDelivery = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).isBusiness),
                        value: _isBusiness,
                        onChanged: (value) => setState(() => _isBusiness = value),
                      ),
                      SwitchListTile(
                        title: Text(AppStrings.of(context).hasDeliveryCabinet),
                        value: _hasDeliveryCabinet,
                        onChanged: (value) => setState(() => _hasDeliveryCabinet = value),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),
              Text(
                AppStrings.of(context).buildingPasswords,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              ..._buildingPasswords.asMap().entries.map((entry) {
                final index = entry.key;
                final password = entry.value;
                return Card(
                  child: ListTile(
                    title: Text(password.buildingNumber),
                    subtitle: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('${AppStrings.of(context).password}: ${password.password}'),
                        if (password.notes != null)
                          Text('${AppStrings.of(context).notes}: ${password.notes}'),
                      ],
                    ),
                    trailing: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.edit),
                          onPressed: () => _editBuildingPassword(index),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete),
                          onPressed: () => _deleteBuildingPassword(index),
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
              const SizedBox(height: 8),
              ElevatedButton.icon(
                onPressed: _addBuildingPassword,
                icon: const Icon(Icons.add),
                label: Text(AppStrings.of(context).addBuildingPassword),
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: _saveCommunity,
                child: Text(widget.community == null ? AppStrings.of(context).add : AppStrings.of(context).save),
              ),
            ],
          ),
        ),
      ),
    );
  }
} 